/*
 * TournamentGUI.java
 *
 * Created on 12/11/2010, 14:33:59
 */
package br.ic.ufal.view;

import br.ufal.ic.core.*;
import br.ufal.ic.dao.*;
import br.ufal.ic.user.User;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;

/**
 * Janela grafica que permite criar novos torneios e tambem visualizar
 * informações sobre os torneios.
 *
 * @author Marcos Paulo
 */
public class TournamentGUI extends JFrame {

    private static final SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    private FacadeDAO facadeDAO;
    private User user;

    /** Creates new form TournamentGUI */
    public TournamentGUI(User user) {

        initComponents();

        this.user = user;
        facadeDAO = FacadeDAO.getInstance();

        initTournamentComboBox();

        initDelegateComboBox();

        setTitle("Bem vindo " + user.getInformation().getName() + "!");

//        facadeDAO.getTournamentDAO().
    }

    /**
     * Inicializa os torneios no tournamentComboBox com os nomes dos torneios.
     */
    private void initTournamentComboBox() {
        List<String> tournaments = new ArrayList<String>();
        for (Tournament tournament : facadeDAO.getTournamentDAO().findAll()) {
            tournaments.add(tournament.getId());
        }
        tournamentComboBox.setModel(new DefaultComboBoxModel(
                tournaments.toArray()));
        tournamentComboBox1.setModel(new DefaultComboBoxModel(
                tournaments.toArray()));

        informationButtonActionPerformed(null);
    }

    /**
     * Inicializa os delegados no delegateComboBox com os nomes dos delegados.
     */
    private void initDelegateComboBox() {
        List<String> delegates = new ArrayList<String>();

        DelegateDAO delegateDAO = FacadeDAO.getInstance().getDelegateDAO();

        for (Delegate delegate : delegateDAO.findAll()) {
            delegates.add(delegate.getInformation().getName());
        }

        delegateComboBox.setModel(new DefaultComboBoxModel(
                delegates.toArray()));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        tournamentComboBox = new javax.swing.JComboBox();
        informationButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tournamentLabel = new javax.swing.JLabel();
        typeLabel = new javax.swing.JLabel();
        creationDateLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        delegateLabel = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        dayToStartLabel = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        createTournamentButton = new javax.swing.JButton();
        delegateComboBox = new javax.swing.JComboBox();
        tournamentTypeComboBox = new javax.swing.JComboBox();
        tournamentNameTextField = new javax.swing.JTextField();
        jLabel10 = new javax.swing.JLabel();
        dayToStartTextField = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel11 = new javax.swing.JLabel();
        tournamentComboBox1 = new javax.swing.JComboBox();
        participateTournamentButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Torneios");
        setResizable(false);

        jLabel2.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel2.setText("Torneio:");

        tournamentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Torneio 1", "Torneio 2" }));

        informationButton.setText("Visualizar informações");
        informationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                informationButtonActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel1.setText("Nome do torneio:");

        jLabel3.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel3.setText("Tipo de torneio:");

        jLabel4.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel4.setText("Data de criação:");

        tournamentLabel.setText("jLabel5");

        typeLabel.setText("jLabel5");

        creationDateLabel.setText("jLabel5");

        jLabel5.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel5.setText("Delegado responsavel:");

        delegateLabel.setText("jLabel5");

        jLabel8.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel8.setText("Dias para começar:");

        dayToStartLabel.setText("jLabel5");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tournamentComboBox, 0, 328, Short.MAX_VALUE))
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addGap(94, 94, 94)
                        .addComponent(informationButton, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(tournamentLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(typeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(creationDateLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel8)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                        .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(delegateLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(dayToStartLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tournamentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(informationButton)
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tournamentLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(typeLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(creationDateLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(dayToStartLabel))
                .addGap(18, 18, 18)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(delegateLabel))
                .addContainerGap(32, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Visualizar torneios", jPanel3);

        jLabel6.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel6.setText("Nome do torneio:");

        jLabel7.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel7.setText("Tipo de torneio:");

        jLabel9.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel9.setText("Delegado responsavel:");

        createTournamentButton.setText("Criar");
        createTournamentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createTournamentButtonActionPerformed(evt);
            }
        });
        createTournamentButton.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                createTournamentButtonKeyPressed(evt);
            }
        });

        delegateComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        tournamentTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "UNOFFICIAL", "OFFICIAL" }));

        jLabel10.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel10.setText("Dias para começar:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel6))
                        .addGap(56, 56, 56)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(tournamentTypeComboBox, 0, 211, Short.MAX_VALUE)
                            .addComponent(tournamentNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(106, 106, 106)
                        .addComponent(createTournamentButton, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jLabel10))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(dayToStartTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 211, Short.MAX_VALUE)
                            .addComponent(delegateComboBox, 0, 211, Short.MAX_VALUE))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(33, 33, 33)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel6)
                    .addComponent(tournamentNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(tournamentTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel10)
                    .addComponent(dayToStartTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel9)
                    .addComponent(delegateComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(37, 37, 37)
                .addComponent(createTournamentButton)
                .addContainerGap(45, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Criar torneio", jPanel1);

        jLabel11.setFont(new java.awt.Font("Arial", 0, 14));
        jLabel11.setText("Torneio:");

        tournamentComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Torneio 1", "Torneio 2" }));

        participateTournamentButton.setText("Participar");
        participateTournamentButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                participateTournamentButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tournamentComboBox1, 0, 318, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(87, 87, 87)
                        .addComponent(participateTournamentButton, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel11)
                    .addComponent(tournamentComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addComponent(participateTournamentButton)
                .addContainerGap(157, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Participe de um torneio", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Metodo que mostra infomações do torneio selecionado.
     * 
     * @param evt
     */
    private void informationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_informationButtonActionPerformed

        Tournament tournament = facadeDAO.getTournamentDAO().findById(
                (String) tournamentComboBox.getSelectedItem());

        if (tournament == null) {
            throw new RuntimeException("torneio não encontrado.");
        }

        tournamentLabel.setText(tournament.getId());
        typeLabel.setText(tournament.getInformation().getType().toString());
        String creationDate = simpleDateFormat.format(
                tournament.getInformation().getCreationDate());
        creationDateLabel.setText(creationDate);

        int dayToStart = tournament.getInformation().getDaysToStart();
        dayToStartLabel.setText((dayToStart == 0 ? "Ja começou" : "" + dayToStart));

        delegateLabel.setText(tournament.getDelegate().getInformation().getName());



    }//GEN-LAST:event_informationButtonActionPerformed

    /**
     * Metodo que cria um novo torneio.
     *
     * @param evt
     */
    private void createTournamentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createTournamentButtonActionPerformed
        try {
            Delegate delegate = FacadeDAO.getInstance().getDelegateDAO().
                    findByName((String) delegateComboBox.getSelectedItem());

            if (delegate == null) {
                throw new RuntimeException("delegado não encontrado.");
            }

            String tournamentName = tournamentNameTextField.getText();

            TournamentType tournamentType = TournamentType.valueOf(
                    (String) tournamentTypeComboBox.getSelectedItem());

            Date creationDate = new Date();

            int dayToStart = Integer.parseInt(dayToStartTextField.getText());

            TournamentInformation information = new TournamentInformation(
                    tournamentName, tournamentType, creationDate, dayToStart);


            Tournament tournament = new Tournament(information, delegate);

            TournamentDAO tournamentDAO = FacadeDAO.getInstance().getTournamentDAO();

            tournamentDAO.save(tournament);

            initTournamentComboBox();

            JOptionPane.showMessageDialog(null, "Torneio criado com sucesso!");

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Falha na hora de criar o"
                    + " torneio\n"
                    + "erro: " + e.getMessage());
        }


    }//GEN-LAST:event_createTournamentButtonActionPerformed

    private void createTournamentButtonKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_createTournamentButtonKeyPressed
        createTournamentButtonActionPerformed(null);
    }//GEN-LAST:event_createTournamentButtonKeyPressed

    private void participateTournamentButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_participateTournamentButtonActionPerformed

        Tournament tournament = facadeDAO.getTournamentDAO().findById(
                (String) tournamentComboBox1.getSelectedItem());

        if (tournament == null) {
            throw new RuntimeException("torneio não encontrado.");
        }

        Competitor competitor = new Competitor(user.getInformation(),
                new Cube(CubeType.CUBE_3X3X3));

        if (!tournament.containCompetitor(competitor)) {

            tournament.addCompetitor(competitor);
            JOptionPane.showMessageDialog(null, "Operação realizada com "
                    + "sucesso!");
            facadeDAO.getTournamentDAO().update(tournament);
        } else {
            JOptionPane.showMessageDialog(null, "você já está "
                    + "participando desse torneio!");
        }

    }//GEN-LAST:event_participateTournamentButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton createTournamentButton;
    private javax.swing.JLabel creationDateLabel;
    private javax.swing.JLabel dayToStartLabel;
    private javax.swing.JTextField dayToStartTextField;
    private javax.swing.JComboBox delegateComboBox;
    private javax.swing.JLabel delegateLabel;
    private javax.swing.JButton informationButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton participateTournamentButton;
    private javax.swing.JComboBox tournamentComboBox;
    private javax.swing.JComboBox tournamentComboBox1;
    private javax.swing.JLabel tournamentLabel;
    private javax.swing.JTextField tournamentNameTextField;
    private javax.swing.JComboBox tournamentTypeComboBox;
    private javax.swing.JLabel typeLabel;
    // End of variables declaration//GEN-END:variables
}
